package com.itheima.huikebackend.controller;

import com.alibaba.fastjson.JSONObject;
import com.itheima.huikebackend.common.R;
import com.itheima.huikebackend.common.Result;
import com.itheima.huikebackend.context.BaseContext;
import com.itheima.huikebackend.dto.SysUserLoginDTO;
import com.itheima.huikebackend.entity.SysUser;
import com.itheima.huikebackend.enums.LoginProEnum;
import com.itheima.huikebackend.service.SysMenuService;
import com.itheima.huikebackend.service.SysUserService;
import com.itheima.huikebackend.utils.JwtUtil;
import com.itheima.huikebackend.vo.CaptchaImageVO;
import com.itheima.huikebackend.vo.RouterVO;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 登录
 *
 * @author iTaotao
 * @version 1.0
 * @date 2023/08/07 16:53:15
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class SysLoginController {
    private final SysUserService sysUserService;
    private final SysMenuService sysMenuService;
    private final JwtUtil jwtUtil;

    @GetMapping("/captchaImage")
    public CaptchaImageVO code() {
        CaptchaImageVO captchaImageVO = sysUserService.code();
        return captchaImageVO;

    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody SysUserLoginDTO sysUserLoginDTO) {
        SysUser loginUser = sysUserService.login(sysUserLoginDTO);
        Map<String, Object> clisa = new HashMap<>();
        clisa.put(LoginProEnum.USER_ID.value, loginUser.getUserId());
        clisa.put("userName", loginUser.getUserName());
        clisa.put("deptId", loginUser.getDeptId());
        String jwt = jwtUtil.createJWT(clisa);

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("token", jwt);
        return Result.successMap(resMap);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getInfo")
    public Map<String, Object> getUserInfo() {
        // 获取用户基本信息
        Map<String, Object> res = sysUserService.getUserInfo((String) BaseContext.getCurrentId());
        log.info((String) BaseContext.getCurrentId());
        return R.success(res);
    }




    @PostMapping("/logout")
    @ApiOperation("退出登录接口")
    public R<?> logout() {
        JSONObject map = new JSONObject();

        return R.success(map);
    }

    @GetMapping("/getRouters")
    public R<List<RouterVO>> getRouters () {
        List<RouterVO> routerVO = sysMenuService.selectTreeMenu((String) BaseContext.getCurrentId());
        return R.success(routerVO);
    }
}
